import {createRouter, createWebHistory} from "vue-router"
import {getJwt} from "@/api/jwt.js";

const routes = [
    {
        name: "main",
        path: "/main",
        component: () => import("@/components/view/Main.vue"),
        meta: { requiresAuth: true }, // 添加认证要求
        children: [{
            name:"coach",
            path: "/main/coach",
            component:()=>import("@/components/view/Coach.vue"),
            meta: { requiresAuth: true }
        },{
            name: "course",
            path: "/main/course",
            component:()=>import("@/components/view/Course.vue"),
            meta: { requiresAuth: true }
        },{
            name: "member",
            path: "/main/member",
            component:()=>import("@/components/view/Member.vue"),
            meta: { requiresAuth: true }
        },{
            name: "reserve",
            path: "/main/reserve",
            component:()=>import("@/components/view/Reserve.vue"),
            meta: { requiresAuth: true }
        },{
            name: "admin",
            path: "/main/admin",
            component:()=>import("@/components/view/Admin.vue"),
            meta: { requiresAuth: true }
        },{
            name: "chart",
            path: "/main/chart",
            component:()=>import("@/components/view/Chart.vue"),
            meta: { requiresAuth: true }
        }]
    },
    {
        name: "login",
        path: "/login",
        component: () => import("@/components/view/Login.vue")
    },
    // 添加默认路由重定向到登录页
    {
        path: '/',
        redirect: '/login'
    }
]

const router = createRouter({
    routes,
    history: createWebHistory()
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
    // 获取JWT token
    const token = getJwt()

    // 检查目标路由是否需要认证
    const requiresAuth = to.matched.some(record => record.meta.requiresAuth)

    // 如果访问需要认证的页面但没有token，重定向到登录页
    if (requiresAuth && !token) {
        next('/login')
    }
    // 如果已经登录且试图访问登录页，则重定向到主页
    else if (to.path === '/login' && token) {
        next('/main/chart')
    }
    // 其他情况允许访问
    else {
        next()
    }
})

export default router
